 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=129 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Checked versus unchecked exceptions
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='checked,exception,unchecked,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Checked versus unchecked exceptions</div>

<div class='main-body'>
 

<br>Unchecked exceptions :
<ul>
<li>
represent <span class='highlight'>defects in the program (bugs)</span> - often invalid arguments passed to a non-private method.
To quote from <em>The Java Programming Language</em>, by Gosling, 
Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, 
generally speaking, reflect errors in your program's logic and cannot be reasonably 
recovered from at run time."
</li>

<li>
are subclasses of <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html">RuntimeException</a></tt>,
and are usually implemented using 
<tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/IllegalArgumentException.html">IllegalArgumentException</a></tt>, 
<tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html">NullPointerException</a></tt>,
or <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/IllegalStateException.html">IllegalStateException</a></tt></li>

<li>
a method is <i>not</i> obliged to establish a policy for the unchecked
exceptions thrown by its implementation (and they almost always do not do so)</li>
</ul>

Checked exceptions :
<ul>
<li>
represent <span class='highlight'>invalid conditions in areas outside the immediate control
of the program</span> (invalid user input, database problems, network outages,
absent files)</li>

<li>
are subclasses of <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/Exception.html">Exception</a></tt></li>

<li>
a method is <i>obliged</i> to establish a policy for all checked exceptions
thrown by its implementation (either pass the checked exception further
up the stack, or handle it somehow)</li>
</ul>


It is somewhat confusing, but note as well that <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html">RuntimeException</a></tt>
(unchecked) is itself a subclass of <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/Exception.html">Exception</a></tt>
(checked).
<p><b>Example 1</b>
<p><a href="TopicActiond08d-2.html">Model Objects</a> are the data-centric classes
used to represent items in a particular domain. Model Object constructors
need to handle both arbitrary user input, and input from underlying database
<tt>ResultSet</tt>s.
<p>Model Object constructors should throw checked exceptions :
<ul>
<li>
the program may have no direct control over user input. This is particularly
true in web applications. It seems safest for a Model Object to treat user
input as having arbitrary, unvalidated content.</li>

<li>
it is not safe for an application to make any assumptions about the state
of the database. The database is an independent entity, and its data may
be changed by various means, outside of any particular application. For
example, data load tools are commonly used to create an initial state for
a new database. Such data can easily violate the constraints built into
a calling application. Thus, the safest assumption is to treat database
<tt>ResultSet</tt>s
as having arbitrary, unvalidated content.</li>
</ul>
Here is an example Model Object, taken from the <a href="TopicAction5f31-2.html">WEB4J</a>
example application. Its constructor throws <tt>ModelCtorException</tt>
(a checked exception) :
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.fish.main.resto;

<span class='keyword'>import</span> hirondelle.web4j.model.ModelCtorException;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelUtil;
<span class='keyword'>import</span> hirondelle.web4j.model.Id;
<span class='keyword'>import</span> hirondelle.web4j.security.SafeText;
<span class='keyword'>import</span> hirondelle.web4j.model.Decimal;
<span class='keyword'>import</span> <span class='keyword'>static</span> hirondelle.web4j.model.Decimal.ZERO;
<span class='keyword'>import</span> hirondelle.web4j.model.Check;
<span class='keyword'>import</span> hirondelle.web4j.model.Validator;
<span class='keyword'>import</span> <span class='keyword'>static</span> hirondelle.web4j.util.Consts.FAILS;

<span class='comment'>/** Model Object for a Restaurant. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Resto {

  <span class='comment'>/**
   Full constructor.
    
   @param aId underlying database internal identifier (optional) 1..50 characters
   @param aName of the restaurant (required), 2..50 characters
   @param aLocation street address of the restaurant (optional), 2..50 characters
   @param aPrice of the fish and chips meal (optional) $0.00..$100.00
   @param aComment on the restaurant in general (optional) 2..50 characters
  */</span>
  <span class='keyword'>public</span> Resto(
    Id aId, SafeText aName, SafeText aLocation, Decimal aPrice, SafeText aComment
  ) <span class='keyword'>throws</span> ModelCtorException {
    fId = aId;
    fName = aName;
    fLocation = aLocation;
    fPrice = aPrice;
    fComment = aComment;
    validateState();
  }
  
  <span class='keyword'>public</span> Id getId() { <span class='keyword'>return</span> fId; }
  <span class='keyword'>public</span> SafeText getName() {  <span class='keyword'>return</span> fName; }
  <span class='keyword'>public</span> SafeText getLocation() {  <span class='keyword'>return</span> fLocation;  }
  <span class='keyword'>public</span> Decimal getPrice() { <span class='keyword'>return</span> fPrice; }
  <span class='keyword'>public</span> SafeText getComment() {  <span class='keyword'>return</span> fComment; }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString(){
    <span class='keyword'>return</span> ModelUtil.toStringFor(<span class='keyword'>this</span>);
  }
  
  <span class='keyword'>@Override</span> <span class='keyword'>public</span>  <span class='keyword'>boolean</span> equals(Object aThat){
    Boolean result = ModelUtil.quickEquals(<span class='keyword'>this</span>, aThat);
    <span class='keyword'>if</span> ( result ==  <span class='keyword'>null</span> ) {
      Resto that = (Resto) aThat;
      result = ModelUtil.equalsFor(
        <span class='keyword'>this</span>.getSignificantFields(), that.getSignificantFields()
      );
    }
    <span class='keyword'>return</span> result;
  }
  
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>int</span> hashCode(){
    <span class='keyword'>if</span> ( fHashCode == <span class='literal'>0</span> ){
      fHashCode = ModelUtil.hashCodeFor(getSignificantFields());
    }
    <span class='keyword'>return</span> fHashCode;
  }
  
  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> Id fId;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fName;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fLocation;
  <span class='keyword'>private</span> <span class='keyword'>final</span> Decimal fPrice;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fComment;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fHashCode;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Decimal HUNDRED = Decimal.from(<span class='literal'>"100"</span>);

  <span class='keyword'>private</span> <span class='keyword'>void</span> validateState() <span class='keyword'>throws</span> ModelCtorException {
    ModelCtorException ex = <span class='keyword'>new</span> ModelCtorException();
    <span class='keyword'>if</span> ( FAILS == Check.optional(fId, Check.range(<span class='literal'>1</span>,<span class='literal'>50</span>)) ) {
      ex.add(<span class='literal'>"Id is optional, 1..50 chars."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.required(fName, Check.range(<span class='literal'>2</span>,<span class='literal'>50</span>)) ) {
      ex.add(<span class='literal'>"Restaurant Name is required, 2..50 chars."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.optional(fLocation, Check.range(<span class='literal'>2</span>,<span class='literal'>50</span>)) ) {
      ex.add(<span class='literal'>"Location is optional, 2..50 chars."</span>);
    }
    Validator[] priceChecks = {Check.range(ZERO, HUNDRED), Check.numDecimalsAlways(<span class='literal'>2</span>)};
    <span class='keyword'>if</span> ( FAILS == Check.optional(fPrice, priceChecks)) {
      ex.add(<span class='literal'>"Price is optional, 0.00 to 100.00."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.optional(fComment, Check.range(<span class='literal'>2</span>,<span class='literal'>50</span>))) {
      ex.add(<span class='literal'>"Comment is optional, 2..50 chars."</span>);
    }
    <span class='keyword'>if</span> ( ! ex.isEmpty() ) <span class='keyword'>throw</span> ex;
  }
  
  <span class='keyword'>private</span> Object[] getSignificantFields(){
    <span class='keyword'>return</span> <span class='keyword'>new</span> Object[] {fName, fLocation, fPrice, fComment};
  }
}
 
</PRE>
<br>
<br><b>Example 2</b>
<p><tt>Args</tt> is a convenient utility class. It performs common validations
on method arguments. If a validation fails, then it throws an unchecked
exception. It is suitable for checking the internal consistency of program,
but not for checking arbitrary user input.
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.web4j.util;

<span class='keyword'>import</span> java.util.regex.*;

<span class='comment'>/**
 Utility methods for common argument validations.

&lt;P&gt;Replaces &lt;tt&gt;if&lt;/tt&gt; statements at the start of a method with 
 more compact method calls.
 
 &lt;P&gt;Example use case.
 &lt;P&gt;Instead of :
 &lt;PRE&gt;
 public void doThis(String aText){
   if (!Util.textHasContent(aText)){
     throw new IllegalArgumentException();
   }
   //..main body elided
 }
 &lt;/PRE&gt;
 &lt;P&gt;One may instead write :
 &lt;PRE&gt;
 public void doThis(String aText){
   Args.checkForContent(aText);
   //..main body elided
 }
 &lt;/PRE&gt;
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Args {
  
  <span class='comment'>/**
   If &lt;code&gt;aText&lt;/code&gt; does not satisfy {@link Util#textHasContent}, then 
   throw an &lt;code&gt;IllegalArgumentException&lt;/code&gt;.
  
   &lt;P&gt;Most text used in an application is meaningful only if it has visible content.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForContent(String aText){
    <span class='keyword'>if</span>( ! Util.textHasContent(aText) ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Text has no visible content"</span>);
    }
  }

  <span class='comment'>/**
   If {@link Util#isInRange} returns &lt;code&gt;false&lt;/code&gt;, then 
   throw an &lt;code&gt;IllegalArgumentException&lt;/code&gt;. 
  
   @param aLow is less than or equal to &lt;code&gt;aHigh&lt;/code&gt;.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForRange( <span class='keyword'>int</span> aNumber, <span class='keyword'>int</span> aLow, <span class='keyword'>int</span> aHigh ) {
    <span class='keyword'>if</span> ( ! Util.isInRange(aNumber, aLow, aHigh) ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(aNumber + <span class='literal'>" not in range "</span> + aLow + <span class='literal'>".."</span> + aHigh);
    }
  }

  <span class='comment'>/**
   If &lt;tt&gt;aNumber&lt;/tt&gt; is less than &lt;tt&gt;1&lt;/tt&gt;, then throw an 
   &lt;tt&gt;IllegalArgumentException&lt;/tt&gt;.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForPositive(<span class='keyword'>int</span> aNumber) {
    <span class='keyword'>if</span> (aNumber &lt; <span class='literal'>1</span>) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(aNumber + <span class='literal'>" is less than 1"</span>);
    }
  }

  <span class='comment'>/**
   If {@link Util#matches} returns &lt;tt&gt;false&lt;/tt&gt;, then 
   throw an &lt;code&gt;IllegalArgumentException&lt;/code&gt;. 
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForMatch(Pattern aPattern, String aText){
    <span class='keyword'>if</span> ( ! Util.matches(aPattern, aText) ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(
        <span class='literal'>"Text "</span> + Util.quote(aText) + <span class='literal'>" does not match '"</span> +aPattern.pattern()+ <span class='literal'>"'"</span>
      );
    }
  }
  
  <span class='comment'>/**
   If &lt;code&gt;aObject&lt;/code&gt; is null, then throw a &lt;code&gt;NullPointerException&lt;/code&gt;.
  
   &lt;P&gt;Use cases :
  &lt;pre&gt;
   doSomething( Football aBall ){
     //1. call some method on the argument : 
     //if aBall is null, then exception is automatically thrown, so 
     //there is no need for an explicit check for null.
     aBall.inflate();
    
     //2. assign to a corresponding field (common in constructors): 
     //if aBall is null, no exception is immediately thrown, so 
     //an explicit check for null may be useful here
     Args.checkForNull( aBall );
     fBall = aBall;
     
     //3. pass on to some other method as parameter : 
     //it may or may not be appropriate to have an explicit check 
     //for null here, according the needs of the problem
     Args.checkForNull( aBall ); //??
     fReferee.verify( aBall );
   }
   &lt;/pre&gt;
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForNull(Object aObject) {
    <span class='keyword'>if</span> ( aObject == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> NullPointerException();
    }
  }
  
  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> Args(){
    <span class='comment'>//empty - prevent construction
</span>  }
  
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiond08d-2.html?Id=187'>Model Objects</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='129'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=129 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
